package uvt.map.graph.algorithm;

import java.util.ArrayList;

import org.openstreetmap.gui.jmapviewer.Coordinate;

import uvt.map.graph.Node;

public class PositionCalculation {
	
	public static double distanceBetweenCoords(Coordinate coord1,Coordinate coord2) {
		double earthRadius = 6371; 
	    double dLat = Math.toRadians(coord2.getLat()-coord1.getLat());
	    double dLon = Math.toRadians(coord2.getLon()-coord1.getLon());
	    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
	               Math.cos(Math.toRadians(coord1.getLat())) * Math.cos(Math.toRadians(coord2.getLat())) *
	               Math.sin(dLon/2) * Math.sin(dLon/2);
	    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	    return earthRadius * c;
	}
	
	public static double bearingBetweenCoords(Coordinate coord1,Coordinate coord2) {
		 double deltaLong = Math.toRadians(coord2.getLon() - coord1.getLon());

		 double lat1 = Math.toRadians(coord1.getLat());
		 double lat2 = Math.toRadians(coord2.getLat());

		 double y = Math.sin(deltaLong) * Math.cos(lat2);
		 double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(deltaLong);
		 double result = Math.toDegrees(Math.atan2(y, x));
		 return (result + 360.0) % 360.0;
	}
	
	public static Coordinate destinationCoordinate(Coordinate start,double dist,double bearing) {
		dist = dist / 6371.0;
		double brng = Math.toRadians(bearing);
		double lat1 = Math.toRadians(start.getLat());
		double lon1 = Math.toRadians(start.getLon());

		double lat2 = Math.asin( Math.sin(lat1)*Math.cos(dist) + Math.cos(lat1)*Math.sin(dist)*Math.cos(brng) );
		double a = Math.atan2(Math.sin(brng)*Math.sin(dist)*Math.cos(lat1), Math.cos(dist)-Math.sin(lat1)*Math.sin(lat2));
		double lon2 = lon1 + a;
		lon2 = (lon2+ 3*Math.PI) % (2*Math.PI) - Math.PI;
		
		return new Coordinate(Math.toDegrees(lat2),Math.toDegrees(lon2));
	}
	
	public static Node getNearestNode(Coordinate actualPosition,ArrayList<Node> list) {
		Node minNode = null;
	    double minDist = 9999;
		for(Node node : list) {
			double dist = distanceBetweenCoords(actualPosition,new Coordinate(node.getLatitude(),
					                                                          node.getLongitude()));
			if(dist < minDist) {
				minDist = dist;
				minNode = node;
			}
		}
		return minNode;
	}
	
	public static double getVehicleHoursOfMovement(String time) {
		double hoursOfMovement = 0;
		String[] parser = time.split(" ");	
		int hour = Integer.valueOf(parser[0]);
		int min = Integer.valueOf(parser[1]);
		if(parser[2].equals("PM"))
			hour += 12.0;
		hoursOfMovement = hour - 7.0 + min / 60.0;			
		return hoursOfMovement;
	}
	
	public static double getVehicleDistanceTraveled(double speed,double hours) {
		double distance = 0.0;
		distance = speed * hours;
		return distance;
	}

}
